package HTTP

import (
	"SQL/util"
	"logs"
	"net/http"
)

// request : groupId  string , userId string
// respon :	Message string
func deleteGroup(w http.ResponseWriter, r *http.Request) {
	var code = Success
	var info = "success"
	var information interface{}

	defer func() {
		writeResult(w, code, info, information)
	}()

	err := r.ParseForm()
	if err != nil {
		code = errParseForm
		logs.Print("From:deleteGroup.ParseForm:---", err.Error())
		info = "From:deleteGroup.ParseForm:---error"
		return
	}

	groupID := r.Form["groupID"]
	userID := r.Form["userID"]

	if userID == nil {
		code = errEmtpyID
		info = "From:deleteGroup:---userID is null"
		return
	}
	if groupID == nil {
		code = errEmtpyID
		info = "From:deleteGroup:---groupID is null"
		return
	}

	info, code, ok := checkOutDeletGroup(userID[0], groupID[0])
	if !ok {
		return
	}
	ok, code, info = deleteGroupFromDB(groupID[0])
	if !ok {
		return
	}

}

func deleteGroupFromDB(id string) (bool, int, string) {
	info := "success"

	if id == "" {
		info = "id is null"
		return false, errEmtpyID, info
	}

	sql := "delete from objects where id = $1"

	_, err := util.Exec(sql, id)
	if err != nil {
		logs.Print("From:deleteGroup.deleteGroupFromDB.Exec:---", err.Error())
		info = "From:deleteGroup.deleteGroupFromDB.Exec:---error"
		return false, errDBExecFailed, info
	}

	return true, Success, info

}

func checkOutDeletGroup(userID string, groupID string) (string, int, bool) {

	info := "success"
	code := Success
	ok := true

	ok, code, info = checkOutId(groupID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---groupID is invlid"
		return info, code, ok
	}

	ok, code, info = checkOutId(userID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---userID is invlid"
		return info, code, ok
	}

	info, code, ok = isManager(userID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---userID is invlid because userID is not managerID"
		return info, code, ok
	}
	info, code, ok = isGroup(groupID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---groupID is invlid because groupID is not group"
		return info, code, ok
	}

	return info, code, ok
}
